package org.flycloud.web.url.controller;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

public class JsonFileProcessor {

	private static final String JSON_SUFFIX = ".json";

	public static void main(String[] args) {
		JSONArray list = load("data/zhangbo");
		System.out.println(JSON.toJSONString(list, true));
	}
	
	public static JSONArray load(String folderPath) {
		List<JSONObject> jsonObjects = new ArrayList<>();
		processFolder("", new File(folderPath), jsonObjects);
		JSONArray jsonArray = new JSONArray();
		jsonArray.addAll(jsonObjects);
		return jsonArray;
	}

	private static void processFolder(String parent, File folder, List<JSONObject> jsonObjects) {
		if (!folder.isDirectory()) {
			throw new IllegalArgumentException("The provided path is not a directory");
		}

		File[] files = folder.listFiles();
		if (files != null) {
			for (File file : files) {
				if (file.isDirectory()) {
					processFolder(parent + "/" + file.getName(), file, jsonObjects); // 递归处理子文件夹
				} else if (file.getName().toLowerCase().endsWith(JSON_SUFFIX)) {
					try {
						if (file.isFile()) {
							JSONObject srcObj = new JSONObject();
							String content = new String(Files.readAllBytes(Paths.get(file.getAbsolutePath())));
							srcObj = JSON.parseObject(content);
							jsonObjects.add(srcObj);
						}
					} catch (IOException e) {
						System.err.println("Error reading JSON from file: " + file.getAbsolutePath());
						e.printStackTrace();
					}
				}
			}
		}
	}
}
